/*
 * Delegator.java
 * This file is the helper tool for server-side application to use as a simple communication tool with the agent
 * after it is intialized with port and monitor port, it provide simple function to the server-side
 * application to call to send connection starting or destroying message to the agent.
 * Server-side application developer can focus on writing logic of the app, and ignore the complexity of the
 * control protocol. He or she will need to insert sendStartMessage(int) or sendDestroyMessage(int) when the
 * connection is setup or when the connection breaks 
 * 
 * */

package wps.servicebus.client;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

public class Delegator {
	private int port;
	private int monitorPort;
	static Logger logger = Logger.getLogger(Delegator.class);
	public Delegator(int port, int monitorPort){
		this.port = port;
		this.monitorPort = monitorPort;
	}
	public int getLocalPort(){
		return port;
	}
	public void sendStartMessage(int processID){
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet("http://127.0.0.1:" + monitorPort + "/manage/?command=start&port="+port+"&processID="+processID);			
		try {
			httpclient.execute(httpget);
			httpget.abort();
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();					
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();					
		}
	}
	public void sendDestroyMessage(int processID){
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet("http://127.0.0.1:" + monitorPort + "/manage/?command=destroy&port="+port+"&processID="+processID);			
		try {				
			httpclient.execute(httpget);
			httpget.abort();
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}			
	}
	public static void main(String[] args){
		Delegator del = new Delegator(123, 9000);
		del.sendStartMessage(1);
		del.sendDestroyMessage(1);
	}
}
